package com.example.smartcity_poverty.ui.AllService.Attorneys.activity.AttMe.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import com.example.smartcity_poverty.App.Companion.getToken
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.logic.util.Util.show
import kotlinx.android.synthetic.main.activity_att_me_all.*
import kotlinx.android.synthetic.main.activity_att_set_all.*
import kotlinx.coroutines.Dispatchers
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

/**
 * 服务评价 @link AttMeAllActivity
 */
class AttSetAllActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_att_set_all)
        title = "服务评价"

        val id = intent.getStringExtra("id")?.toInt()
        var number: Int? = null

        // 监听星级选择
        ratingBar.setOnRatingBarChangeListener { _, fl, _ ->
            number = fl.toInt()
        }

        // 点击提交评价
        attAllSetBtnOk.setOnClickListener {
            if (attAllSetContent.text.toString().isNotEmpty()){
                if (number != 0) {
                    coroutine(Dispatchers.IO){
                        // 提交评价
                        api.getAttSetAll(getToken(), JSONObject().apply {
                            put("id", id)
                            put("evaluate", attAllSetContent.text.toString())
                            put("score", number?.toInt())
                        }.toString().toRequestBody("application/json".toMediaTypeOrNull())).apply {
                            if (this.code == "200"){
                                runOnUiThread { this.msg.show() }
                            }else runOnUiThread { this.msg.show() }
                        }
                    }
                }else runOnUiThread { "评价不能低于1星！".show() }
            }else runOnUiThread { "评价内容或手机号码不能为空！".show() }
        }



    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}